package com.item.yxlottery.yxlottery.activity;

/*
 *------------------------------
 * @创建者      Administrator
 * @创建时间    2016/12/16 15:12
 * @文件描述    双色球界面
 *------------------------------
 */

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.flyco.animation.Attention.Swing;
import com.flyco.animation.SlideExit.SlideBottomExit;
import com.flyco.dialog.widget.NormalDialog;
import com.item.yxlottery.yxlottery.R;
import com.item.yxlottery.yxlottery.adapter.SsqBlueBallAdapter;
import com.item.yxlottery.yxlottery.adapter.SsqRedBallAdapter;
import com.item.yxlottery.yxlottery.base.BaseActivity;
import com.item.yxlottery.yxlottery.bean.BallBean;
import com.item.yxlottery.yxlottery.callback.MyStringCallBack;
import com.item.yxlottery.yxlottery.common.Constant;
import com.item.yxlottery.yxlottery.utils.CountUtil;
import com.item.yxlottery.yxlottery.utils.RedNumberUtil;
import com.item.yxlottery.yxlottery.utils.UrlUtil;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

public class ShuangSeQiuActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.tv_shuangseqiu_desctext)
    TextView mTvDesctext;

    @Bind(R.id.all_shuangseqiu_random)
    LinearLayout mAllRandom;

    @Bind(R.id.rv_shuangseqiu_rebbar)
    RecyclerView mRvRebbar;

    @Bind(R.id.rv_shuangseqiu_bluebar)
    RecyclerView mRvBluebar;

    @Bind(R.id.tv_shuangseqiu_money)
    TextView mTvMoney;

    @Bind(R.id.bt_shuangseqiu_clear)
    Button mBtClear;

    @Bind(R.id.bt_shuangseqiu_sure)
    Button mBtSure;

    @Bind(R.id.tv_shuangseqiu_warning)
    TextView tv_warning;

    private ImageButton mIbActionbarRight;
    private ArrayList<BallBean> mRedBarList;
    private ArrayList<BallBean> mBlueBarList;
    private SsqRedBallAdapter mRedBarAdapter;
    private SsqBlueBallAdapter mBlueBarAdapter;
    private ArrayList<String> mSelectorRedBarList = new ArrayList<>();//存储选中的红球
    private ArrayList<String> mSelectorBlueBarList = new ArrayList<>();//存储选中的蓝球
    private boolean mWindowState;//PopupWindow是否显示
    private PopupWindow mPopupWindow;
    private boolean mJumpState;//是否是从购买界面跳转过来
    private String mNextPeriod;

    @Override
    protected void setCustomActionBar(ImageButton ibActionbarLeft, TextView tvActionBarTitle, ImageButton ibActionbarRight, AutoRelativeLayout layoutActionbar) {
        ibActionbarLeft.setImageResource(R.drawable.leftarrow);
        ibActionbarLeft.setOnClickListener(this);
        ibActionbarRight.setImageResource(R.drawable.menu);
        ibActionbarRight.setOnClickListener(this);
        tvActionBarTitle.setText("双色球");
        mIbActionbarRight = ibActionbarRight;
    }

    @Override
    protected View initView() {
        View view = View.inflate(this, R.layout.activity_shuangseqiu, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {
        //获取期数和开奖信息
       getNextOpenInfo();

        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("jump")) {
            mJumpState = true;
        } else {
            mJumpState = false;
        }
        mTvDesctext.setText(RedNumberUtil.numberWarning("请至少选择6个红球，1个篮球", 0xffff0000, 0xff0000ff));
        mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 0 元", 0xffff0000));

        mRedBarList = new ArrayList<>();//红球
        for (int i = 1; i < 34; i++) {
            if (i < 10) {
                mRedBarList.add(new BallBean("0" + i));
            } else {
                mRedBarList.add(new BallBean(i + ""));
            }
        }
        mRedBarAdapter = new SsqRedBallAdapter(R.layout.item_lottery_redball, mRedBarList);
        mRedBarAdapter.openLoadAnimation();
        mRvRebbar.setLayoutManager(new GridLayoutManager(this, 7) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvRebbar.setAdapter(mRedBarAdapter);

        mBlueBarList = new ArrayList<>();//蓝球
        for (int i = 1; i < 17; i++) {
            if (i < 10) {
                mBlueBarList.add(new BallBean("0" + i));
            } else {
                mBlueBarList.add(new BallBean(i + ""));
            }
        }
        mBlueBarAdapter = new SsqBlueBallAdapter(R.layout.item_lottery_blueball, mBlueBarList);
        mBlueBarAdapter.openLoadAnimation();
        mRvBluebar.setLayoutManager(new GridLayoutManager(this, 7) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        mRvBluebar.setAdapter(mBlueBarAdapter);
    }

    private void getNextOpenInfo() {
        String model = "ssq";//这期双色球开奖截止等信息接口
        OkHttpUtils.post().url(UrlUtil.getNextOpenInfoUrl()).addParams("lotteryType",model).build().execute(new MyStringCallBack(this, true) {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                JSONObject parse = (JSONObject) JSON.parse(response);
                if (parse.getString("error_code").equals(Constant.SUCCESS)){
                    JSONObject attrs = (JSONObject) JSON.parse(parse.getString("attrs"));
                    String nextOpenTime = attrs.getString("nextOpenTime");//下期开奖时间"21:15"
                    String nextBuyBefore = attrs.getString("nextBuyBefore");//下期购彩截止时间"2016-12-29 19:20"
                    mNextPeriod =    attrs.getString("nextPeriod"); //下期期号"2016152"
                    tv_warning.setText(mNextPeriod+"期 "+nextBuyBefore+"截至投注，"+nextOpenTime+"开奖");
                }else {
                    ToastUtils.showShortToastSafe(ShuangSeQiuActivity.this,parse.getString("msg"));
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        mRvRebbar.addOnItemTouchListener(new OnItemClickListener() {//红球区点击事件
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter adapter, View view, int position) {
                //记录选中的红球
                if (mSelectorRedBarList.size() < 20) {//少于20个,还可以继续选取
                    if (mSelectorRedBarList.contains((position + 1) + "")) {
                        mSelectorRedBarList.remove((position + 1) + "");
                    } else {
                        mSelectorRedBarList.add((position + 1) + "");
                    }
                } else if (mSelectorRedBarList.size() == 20 && mSelectorRedBarList.contains((position + 1) + "")) {//已经选取20个,只能作取消选择操作
                    mSelectorRedBarList.remove((position + 1) + "");
                } else {
                    showWarningDialog();
                    return;
                }
                //选中红球的状态变化
                if (view.isSelected()) {
                    setBarState(view, 1, false);
                } else {
                    setBarState(view, 1, true);
                }
                //显示计算后的金额
                if (mSelectorRedBarList.size() >= 6 && mSelectorBlueBarList.size() >= 1) {
                    mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 " + CountUtil.count(mSelectorRedBarList, mSelectorBlueBarList) * 2 + " 元", 0xffff0000));
                } else {
                    mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 0 元", 0xffff0000));
                }
            }
        });
        mRvBluebar.addOnItemTouchListener(new OnItemClickListener() {//蓝球区的点击事件
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter adapter, View view, int position) {
                //记录选中的蓝球
                if (mSelectorBlueBarList.contains((position + 1) + "")) {
                    mSelectorBlueBarList.remove((position + 1) + "");
                } else {
                    mSelectorBlueBarList.add((position + 1) + "");
                }
                //选中蓝球状态的变化
                if (view.isSelected()) {
                    setBarState(view, 2, false);
                } else {
                    setBarState(view, 2, true);
                }
                //显示计算后的金额
                if (mSelectorRedBarList.size() >= 6 && mSelectorBlueBarList.size() >= 1) {
                    mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 " + CountUtil.count(mSelectorRedBarList, mSelectorBlueBarList) * 2 + " 元", 0xffff0000));
                } else {
                    mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 0 元", 0xffff0000));
                }
            }
        });
        mAllRandom.setOnClickListener(this);
        mBtClear.setOnClickListener(this);
        mBtSure.setOnClickListener(this);
    }

    /*- 红球超过20个后的提醒框 -*/
    private void showWarningDialog() {
        final NormalDialog dialog = new NormalDialog(ShuangSeQiuActivity.this);
        dialog.content("红球最多只能选取20个，\n您可以点击号码取消选择！").contentGravity(Gravity.CENTER).style(NormalDialog.STYLE_TWO)
                .btnNum(1).btnText("确定").btnTextColor(0xff000000).btnTextSize(16f)
                .showAnim(new Swing()).dismissAnim(new SlideBottomExit()).show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_actionbar_left:
                finish();
                break;
            case R.id.ib_actionbar_right:
                if (mWindowState == false) {
                    mWindowState = true;
                    showPopupWindow();
                } else {
                    mPopupWindow.dismiss();
                }
                break;
            case R.id.all_shuangseqiu_random:
                clearBarState();
                randomLottery();
                break;
            case R.id.bt_shuangseqiu_clear:
                clearBarState();
                mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 0 元", 0xffff0000));
                break;
            case R.id.bt_shuangseqiu_sure:
                if (mSelectorBlueBarList.size() == 0 && mSelectorRedBarList.size() == 0) {
                    randomLottery();
                } else if (mSelectorRedBarList.size() > 0 && mSelectorRedBarList.size() < 6) {
                    Toast.makeText(this, "请至少选择6个红球", Toast.LENGTH_SHORT).show();
                } else if (mSelectorRedBarList.size() >= 6 && mSelectorBlueBarList.size() == 0) {
                    Toast.makeText(this, "请至少选择1个蓝球", Toast.LENGTH_SHORT).show();
                } else if (mSelectorRedBarList.size() < 6 && mSelectorBlueBarList.size() > 0) {
                    Toast.makeText(this, "请至少选择6个红球", Toast.LENGTH_SHORT).show();
                } else {
                    StringBuffer redBuffer = new StringBuffer();
                    for (String red : mSelectorRedBarList) {
                        redBuffer.append(red + ",");
                    }
                    StringBuffer blueBuff = new StringBuffer();
                    for (String blue : mSelectorBlueBarList) {
                        blueBuff.append(blue + ",");
                    }
                    Intent intent = new Intent(this, BuySsqActivity.class);
                    intent.putExtra("red", redBuffer.toString());
                    intent.putExtra("blue", blueBuff.toString());
                    intent.putExtra("nextPeriod", mNextPeriod);
                    if (mJumpState) {
                        setResult(0, intent);
                        this.finish();
                    } else {
                        startActivity(intent);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                clearBarState();//跳转之后清空选中的球
                                mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 0 元", 0xffff0000));
                            }
                        }, 1000);
                    }
                }
                break;
            case R.id.bt_ssq_pw_number:
                mPopupWindow.dismiss();
                startActivity(new Intent(this, OpenSsqNumberActivity.class));
                break;
            case R.id.bt_ssq_pw_play:
                mPopupWindow.dismiss();
                break;
        }
    }

    /*- 随机一注 -*/
    private void randomLottery() {
        Random random = new Random();
        while (mSelectorRedBarList.size() < 6) {
            int redNum = random.nextInt(33) + 1;
            if (mSelectorRedBarList.contains(redNum + "")) {
                continue;
            }
            mSelectorRedBarList.add(redNum + "");
            setBarState(mRvRebbar.getChildAt(redNum - 1), 1, true);//设置随机红球的状态
        }
        int blueNum = random.nextInt(16) + 1;
        mSelectorBlueBarList.add(blueNum + "");
        setBarState(mRvBluebar.getChildAt(blueNum - 1), 2, true);//设置随机蓝球状态
        mTvMoney.setText(RedNumberUtil.numberWarning("投注金额 " + CountUtil.count(mSelectorRedBarList, mSelectorBlueBarList) * 2 + " 元", 0xffff0000));
    }

    /*- 显示PopupWindow -*/
    private void showPopupWindow() {
        View inflate = LinearLayout.inflate(this, R.layout.item_shuangseqiu_popupwindow, null);
        mPopupWindow = new PopupWindow(inflate);
        mPopupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(false);//是否获取焦点,获取焦点之后,点击其他的按钮不会触发对应的点击事件
        backgroundAlpha(this, 0.6f);
        Button btNumber = (Button) inflate.findViewById(R.id.bt_ssq_pw_number);
        Button btPlay = (Button) inflate.findViewById(R.id.bt_ssq_pw_play);
        mPopupWindow.showAsDropDown(mIbActionbarRight);
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mWindowState = false;
                backgroundAlpha(ShuangSeQiuActivity.this, 1f);
            }
        });
        btNumber.setOnClickListener(this);
        btPlay.setOnClickListener(this);
    }

    /*- 设置屏幕的背景透明度 -*/
    public void backgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
        return super.onTouchEvent(event);
    }

    /*- 清除操作 -*/
    private void clearBarState() {
        if (mSelectorRedBarList.size() > 0) {
            for (String number : mSelectorRedBarList) {
                setBarState(mRvRebbar.getChildAt(Integer.parseInt(number) - 1), 1, false);
            }
        }
        if (mSelectorBlueBarList.size() > 0) {
            for (String number : mSelectorBlueBarList) {
                setBarState(mRvBluebar.getChildAt(Integer.parseInt(number) - 1), 2, false);
            }
        }
        mSelectorRedBarList.clear();
        mSelectorBlueBarList.clear();
    }

    /*- 设置选中球的状态 -*/
    private void setBarState(View childView, int i, boolean bool) {
        childView.setSelected(bool);
        TextView bar = null;
        if (i == 1) {
            bar = (TextView) childView.findViewById(R.id.tv_item_lottery_redball);
        } else {
            bar = (TextView) childView.findViewById(R.id.tv_item_lottery_blueball);
        }
        bar.setSelected(bool);
    }
}